﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Collections;

namespace System.Qizx.Xdm {
    public class XdmNodeList : IEnumerator {
        // Fields
        internal XdmNode child;
        internal XdmNode container;
        internal bool isFirst;
        private int _count = -1;

        public IEnumerator GetEnumerator() {
            return this;
        }

        // Methods
        internal XdmNodeList(XdmNode container) {
            this.container = container;
            this.child = container.FirstChild as XdmNode;
            this.isFirst = true;
        }

        internal bool MoveNext() {
            if (this.isFirst) {
                this.child = this.container.FirstChild;
                this.isFirst = false;
            } else if (this.child != null) {
                this.child = this.child.NextSibling as XdmNode;
            }
            return (this.child != null);
        }

        bool IEnumerator.MoveNext() {
            return this.MoveNext();
        }

        void IEnumerator.Reset() {
            this.isFirst = true;
            this.child = this.container.FirstChild as XdmNode;
        }

        // Properties
        internal XdmNode Current {
            get {
                if (this.isFirst || (this.child == null)) {
                    throw new InvalidOperationException("get current node before moveNext");
                }
                return this.child;
            }
        }

        /// <summary>
        /// Gets the count.
        /// </summary>
        /// <value>The count.</value>
        public int Count {
            get {
                if (_count == -1) {
                    _count = 0;
                    while (this.MoveNext()) {
                        _count++;
                    }
                }
                return _count;
            }
        }

        object IEnumerator.Current {
            get {
                return this.Current;
            }
        }
    }

}
